<template>
    <div class="order-management-container">
        <!-- 1. 搜索栏：订单专属查询条件 -->
        <div class="search-bar">
            <!-- 用户名查询 -->
            <input type="text" v-model="searchParams.loginName" placeholder="输入用户名" @keyup.enter="fetchOrderData" />

            <!-- 订单状态查询（下拉选择，匹配状态码与中文） -->
            <select v-model="searchParams.status" @change="fetchOrderData">
                <option value="">全部订单状态</option>
                <option value="1">未支付</option>
                <option value="2">已支付</option>
                <option value="3">订单关闭</option>
            </select>

            <!-- 订单编号查询 -->
            <input type="text" v-model="searchParams.serialNumber" placeholder="输入订单编号" @keyup.enter="fetchOrderData" />

            <!-- 下单时间筛选 -->
            <span>下单时间</span>
            <input type="date" v-model="searchParams.startTime" class="date-input" @change="validateTimeRange" />
            -
            <input type="date" v-model="searchParams.endTime" class="date-input" @change="validateTimeRange" />

            <span v-if="timeError" class="time-error">{{ timeError }}</span>

            <!-- 操作按钮 -->
            <button class="search-btn" @click="fetchOrderData">
                <i class="icon-search"></i> 搜索
            </button>
            <button class="reset-btn" @click="resetSearch" v-show="hasSearchCondition">
                重置
            </button>
        </div>

        <div class="loading-state" v-if="isLoading">
            <p>加载中...</p>
        </div>

        <div class="order-table-container" v-else>
            <div class="table-header">
                <div class="table-cell expand-column">展开</div>
                <div class="table-cell order-id-column">订单ID</div>
                <div class="table-cell user-column">用户名</div>
                <div class="table-cell address-column">收货地址</div>
                <div class="table-cell time-column">下单时间</div>
                <div class="table-cell amount-column">订单总金额</div>
                <div class="table-cell status-column">订单状态</div>
                <div class="table-cell action-column">操作</div>
            </div>

            <!-- 表格内容区 -->
            <div class="table-body">
                <!-- 空数据提示 -->
                <div class="empty-state" v-if="orderList.length === 0">
                    <p>{{ hasSearchCondition ? "没有找到匹配的订单" : "暂无订单数据" }}</p>
                </div>

                <!-- 订单列表+详情列表 -->
                <div v-for="order in orderList" :key="order.id">
                    <!--订单 -->
                    <div class="table-row order-row" @click="toggleOrderExpand(order.id)">
                        <div class="table-cell expand-column">
                            <!-- 展开/折叠按钮 -->
                            <button class="expand-btn" :class="{ expanded: order.isExpanded }">
                                {{ order.isExpanded ? "▼" : "▶" }}
                            </button>
                        </div>
                        <div class="table-cell order-id-column">{{ order.id }}</div>
                        <div class="table-cell user-column">{{ order.loginName || "未知用户" }}</div>
                        <div class="table-cell address-column">{{ order.userAddress }}</div>
                        <div class="table-cell time-column">{{ order.createTime }}</div>
                        <div class="table-cell amount-column">¥{{ order.cost }}</div>
                        <div class="table-cell status-column">
                            <span :class="getStatusClass(order.status)">{{ getStatusText(order.status) }}</span>
                        </div>
                        <div class="table-cell action-column" v-if="order.status === 1">
                            <button class="update-status-btn" @click.stop="closeOrder(order.id)">
                                关闭订单
                            </button>
                        </div>
                        <div class="table-cell action-column" v-else-if="order.status !== 1">
                            <button class="update-status-unbtn" >
                                无法操作
                            </button>
                        </div>

                    </div>

                    <!-- 3.2 订单详情子行（折叠展示） -->
                    <div class="detail-row" v-if="order.isExpanded">
                        <div class="detail-table">
                            <!-- 详情表格标题 -->
                            <div class="detail-table-header">
                                <div class="detail-cell img-column">商品图片</div>
                                <div class="detail-cell name-column">商品名称</div>
                                <div class="detail-cell quantity-column">购买数量</div>
                                <div class="detail-cell price-column">单价（元）</div>
                                <div class="detail-cell subtotal-column">小计（元）</div>
                            </div>
                            <!-- 详情表格内容 -->
                            <div class="detail-table-body">
                                <div class="detail-table-row" v-for="detail in order.easyBuyOrderDetails"
                                    :key="detail.id">
                                    <div class="detail-cell img-column">
                                        <img :src="`http://117.72.153.227/image/${detail.product.fileName || ''}`"
                                            alt="商品图片" class="product-img">
                                    </div>
                                    <div class="detail-cell name-column">{{ detail.product.productName || "未知商品" }}
                                    </div>
                                    <div class="detail-cell quantity-column">{{ detail.quantity || 0 }}</div>
                                    <div class="detail-cell price-column">¥{{ (detail.cost || 0).toFixed(2) }}</div>
                                    <div class="detail-cell subtotal-column">¥{{ (detail.quantity * (detail.cost ||
                                        0)).toFixed(2) }}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 4. 分页控件（以订单为分页单位） -->
        <div class="pagination-container" v-if="orderList.length > 0 && !isLoading">
            <button class="page-btn" :disabled="currentPage === 1 || isLoading" @click="goToFirstPage">首页</button>
            <button class="page-btn" :disabled="currentPage === 1 || isLoading" @click="goToPrevPage">上一页</button>
            <span class="page-info">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
            <button class="page-btn" :disabled="currentPage === totalPages || isLoading"
                @click="goToNextPage">下一页</button>
            <button class="page-btn" :disabled="currentPage === totalPages || isLoading"
                @click="goToLastPage">末页</button>
            <select v-model="pageSize" @change="handlePageSizeChange" class="page-size-select" :disabled="isLoading">
                <option value="5">每页5条</option>
                <option value="10">每页10条</option>
                <option value="20">每页20条</option>
            </select>
        </div>
    </div>
</template>

<script>
import axios from "axios";

export default {
    name: "ProductOrderList",
    data() {
        return {
            orderList: [],          // 订单列表（父数据）
            currentPage: 1,         // 当前页码（按订单分页）
            pageSize: 10,           // 每页订单数
            totalItems: 0,          // 总订单数
            isLoading: false,       // 加载状态
            timeError: "",          // 时间错误信息

            searchParams: {
                loginName: "",        // 用户名
                status: "",           // 订单状态（空表示全部）
                serialNumber: "",     // 订单编号
                startTime: "",        // 下单开始时间
                endTime: ""           // 下单结束时间
            }
        };
    },
    computed: {
        hasSearchCondition() {
            return Object.values(this.searchParams).some(val => val !== "");
        },
        totalPages() {
            return Math.ceil(this.totalItems / this.pageSize);
        }
    },
    created() {
        this.fetchOrderData();
    },
    methods: {
        //加载分页信息
        async fetchOrderData() {
            this.validateTimeRange();
            // 如果有时间错误，不执行搜索
            if (this.timeError) {
                return;
            }
            this.isLoading = true;
            try {
                const params = {
                    pageNum: this.currentPage,
                    pageSize: this.pageSize,
                    ...this.searchParams
                };
                //删除空值
                Object.keys(params).forEach(key => {
                    if (params[key] === "" || params[key] === undefined) {
                        delete params[key];
                    }
                });

                const response = await axios.get("/api/order/getAllOrder", { params });
                const { pageInfo } = response.data;

                this.orderList = (pageInfo.list || []).map(order => ({
                    ...order,
                    isExpanded: false // 初始默认折叠
                }));
                this.totalItems = pageInfo.total || 0;
            } catch (error) {
                console.error("获取订单列表失败:", error);
                this.$message.error(`获取订单列表失败: ${error.response?.data?.message || error.message}`);
            } finally {
                this.isLoading = false;
            }
        },

        // 订单详情展开/折叠控制
        toggleOrderExpand(orderId) {
            const targetOrder = this.orderList.find(order => order.id === orderId);
            if (targetOrder) {
                targetOrder.isExpanded = !targetOrder.isExpanded;
            }
        },
        //订单状态码映射
        getStatusText(status) {
            const statusMap = {
                1: "未支付",
                2: "已支付",
                3: "订单关闭",
                4: "已退款"
            };
            return statusMap[status] || "未知状态";
        },

        getStatusClass(status) {
            const classMap = {
                1: "status-pending",   // 待付款（橙色）
                2: "status-shipping",  // 已付款（蓝色）
                3: "status-delivered", // 已关闭（绿色）
                4: "status-refund",    // 已退款（红色）
            };
            return classMap[status] || "status-default";
        },
        // 重置搜索条件
        resetSearch() {
            this.searchParams = {
                loginName: "",
                status: "",
                serialNumber: "",
                startTime: "",
                endTime: ""
            };
            this.timeError = "";
            this.currentPage = 1;
            this.fetchOrderData();
        },
        // 验证时间范围
        validateTimeRange() {
            this.timeError = "";

            if (this.searchParams.startTime && this.searchParams.endTime) {
                const start = new Date(this.searchParams.startTime);
                const end = new Date(this.searchParams.endTime);
                if (start > end) {
                    this.timeError = "开始时间不能晚于结束时间";
                }
            }
        },
        // 分页操作
        goToFirstPage() {
            if (this.currentPage > 1) {
                this.currentPage = 1;
                this.fetchOrderData();
            }
        },
        goToPrevPage() {
            if (this.currentPage > 1) {
                this.currentPage--;
                this.fetchOrderData();
            }
        },
        goToNextPage() {
            if (this.currentPage < this.totalPages) {
                this.currentPage++;
                this.fetchOrderData();
            }
        },
        goToLastPage() {
            if (this.currentPage < this.totalPages) {
                this.currentPage = this.totalPages;
                this.fetchOrderData();
            }
        },
        handlePageSizeChange() {
            this.currentPage = 1; // 切换每页条数时重置到第一页
            this.fetchOrderData();
        },

        // 关闭未支付订单
        async closeOrder(orderId) {
            if (!confirm('确定要关闭此订单吗？')) {
                return;
            }

            try {
                await axios.post("/api/order/changeStatus", {
                    orderId: orderId,
                    status: 3 // 3表示订单关闭状态
                });

                this.$message.success("订单已成功关闭");
                this.fetchOrderData(); // 刷新订单列表
            } catch (error) {
                console.error("关闭订单失败:", error);
                this.$message.error(`关闭订单失败: ${error.response?.data?.message || error.message}`);
            }
        }
    }
};
</script>

<style scoped>
/* 1. 容器基础样式 */
.order-management-container {
    padding: 20px;
    font-family: "Microsoft YaHei", sans-serif;
}

/* 2. 搜索栏样式 */
.search-bar {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
    padding: 12px 20px;
    background-color: #f5f5f5;
    border-radius: 4px;
    align-items: center;
    flex-wrap: wrap;
    /* 适配小屏幕 */
}

.search-bar input,
.search-bar select {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
    min-width: 160px;
}

.search-bar select {
    width: 140px;
}

.date-input {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
    width: 160px;
}

.search-btn,
.reset-btn {
    padding: 8px 15px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    display: inline-flex;
    align-items: center;
    gap: 5px;
    white-space: nowrap;
}

.search-btn {
    background-color: #1890ff;
    color: white;
}

.reset-btn {
    background-color: #f5f5f5;
    color: #666;
    border: 1px solid #ddd;
}

/* 3. 加载状态样式 */
.loading-state {
    padding: 40px 0;
    text-align: center;
    color: #666;
    font-size: 16px;
}

/* 4. 订单表格（父表）样式 */
.order-table-container {
    width: 80%;
    min-width: 1000px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.table-header {
    display: flex;
    background-color: #f5f5f5;
    border-bottom: 1px solid #e0e0e0;
    font-weight: bold;
    color: #333;
}

.table-row {
    display: flex;
    border-bottom: 1px solid #e0e0e0;
    transition: background-color 0.2s;
    cursor: pointer;
}

.table-row:hover {
    background-color: #f9f9f9;
}

.table-cell {
    padding: 12px 16px;
    line-height: 1.5;
    word-break: break-all;
    display: flex;
    align-items: center;
}

/* 4.1 父表列宽配置 */
.expand-column {
    width: 60px;
    flex-shrink: 0;
    justify-content: center;
}

.order-id-column {
    width: 50px;
    flex-shrink: 0;
    color: #666;
}

.user-column {
    width: 120px;
    flex-shrink: 0;
}

.address-column {
    flex: 2;
    min-width: 150px;
}

.time-column {
    width: 180px;
    flex-shrink: 0;
    color: #666;
}

.amount-column {
    width: 120px;
    flex-shrink: 0;
    color: #ff4d4f;
    /* 金额红色突出 */
    font-weight: 500;
}

.status-column {
    width: 120px;
    flex-shrink: 0;
}

.action-column {
    width: 120px;
    flex-shrink: 0;
    justify-content: center;
}


.expand-btn {
    background: none;
    border: none;
    font-size: 16px;
    cursor: pointer;
    color: #1890ff;
}


.status-pending {
    padding: 2px 8px;
    border-radius: 12px;
    background-color: #fff7e6;
    color: #fa8c16;
    font-size: 12px;
}

.status-shipping {
    padding: 2px 8px;
    border-radius: 12px;
    background-color: #e6f7ff;
    color: #1890ff;
    font-size: 12px;
}

.status-delivered {
    padding: 2px 8px;
    border-radius: 12px;
    background-color: #f0fff4;
    color: #52c41a;
    font-size: 12px;
}

.status-refund {
    padding: 2px 8px;
    border-radius: 12px;
    background-color: #fff1f0;
    color: #ff4d4f;
    font-size: 12px;
}


.detail-row {
    background-color: #fafafa;
    border-bottom: 1px solid #e0e0e0;
}

.detail-table {
    width: 100%;
    padding: 16px;
}

.detail-table-header {
    display: flex;
    background-color: #f0f0f0;
    border-radius: 4px 4px 0 0;
    font-weight: bold;
    color: #333;
}

.detail-table-body {
    border: 1px solid #e0e0e0;
    border-top: none;
    border-radius: 0 0 4px 4px;
}

.detail-table-row {
    display: flex;
    border-bottom: 1px solid #e0e0e0;
}

.detail-table-row:last-child {
    border-bottom: none;
}

.detail-cell {
    padding: 12px 16px;
    line-height: 1.5;
    display: flex;
    align-items: center;
}


.img-column {
    width: 80px;
    flex-shrink: 0;
    justify-content: center;
}

.name-column {
    flex: 2;
    min-width: 200px;
}

.quantity-column {
    width: 100px;
    flex-shrink: 0;
    justify-content: center;
    color: #666;
}

.price-column {
    width: 120px;
    flex-shrink: 0;
    justify-content: center;
    color: #666;
}

.subtotal-column {
    width: 120px;
    flex-shrink: 0;
    justify-content: center;
    color: #ff4d4f;
    font-weight: 500;
}


.product-img {
    width: 60px;
    height: 60px;
    object-fit: cover;
    border-radius: 4px;
    border: 1px solid #eee;
}

.update-status-btn {
    padding: 6px 10px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    transition: background-color 0.2s;
    background-color: #2f54eb;
    color: white;
}

.update-status-unbtn {
    padding: 6px 10px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    transition: background-color 0.2s;
    background-color: #7b7b7b;
    color: rgb(65, 65, 65);
}

.update-status-btn:hover {
    background-color: #1d39c4;
}


.empty-state {
    padding: 60px 0;
    text-align: center;
    color: #999;
    border-bottom: 1px solid #e0e0e0;
}


.pagination-container {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 20px 0;
    gap: 15px;
    padding: 10px;
    flex-wrap: wrap;
}

.page-btn {
    padding: 6px 12px;
    background-color: #f5f5f5;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
}

.page-btn:hover:not(:disabled) {
    background-color: #1890ff;
    color: white;
    border-color: #1890ff;
}

.page-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.page-info {
    font-size: 14px;
    color: #666;
}

.page-size-select {
    padding: 6px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background-color: white;
}


.icon-search::before {
    content: "🔍";
}

.time-error {
    color: #ff4d4f;
    font-size: 12px;
    margin-left: 10px;
    white-space: nowrap;
}
</style>
